#!/bin/bash

# ========== 配置区域 ==========
SOURCE="root@10.27.71.2:/mnt/diskpoolG/服务器/"
BACKUP_ROOT="/mnt/disk"

LOCK_FILE="${BACKUP_ROOT}/.rsync_backup.lock"
MAIN_LOG="${BACKUP_ROOT}/backup.log"
TIMESTAMP=$(date +%Y%m%d%H%M%S)
CURRENT_BACKUP="${BACKUP_ROOT}/服务器副本_${TIMESTAMP}_进行中"

# ========== 防重复运行检查 ==========
if [ -f "$LOCK_FILE" ]; then
    echo "$(date '+%F %T') 检测到锁文件，跳过本次执行" >> "$MAIN_LOG"
    exit 1
fi
touch "$LOCK_FILE"

# ========== 准备备份目录 ==========
mkdir -p "$CURRENT_BACKUP"
exec > >(tee -a "${CURRENT_BACKUP}/rsync详细日志.log") 2>&1

# ========== 查找增量基准 ==========
LAST_COMPLETED=$(
    find "${BACKUP_ROOT}" -maxdepth 1 -type d \
    -name "*_完成*" -printf "%T@ %p\n" | 
    sort -n | tail -1 | cut -d' ' -f2-
)
[ -n "$LAST_COMPLETED" ] && LINK_PARAM="--link-dest=${LAST_COMPLETED}"

# ========== 日志头信息（置顶保留） ==========
{
    echo "======= 备份元信息（永久保留） ======="
    echo "开始时间: $(date '+%F %T')"
    echo "源路径: $SOURCE"
    echo "目标路径: $CURRENT_BACKUP"
    if [ -n "$LAST_COMPLETED" ]; then
        echo "增量基准: $LAST_COMPLETED"
    else
        echo "增量基准: 无（首次完整备份）"
    fi
    echo "==================================="
} | tee -a "$MAIN_LOG" "${CURRENT_BACKUP}/rsync详细日志.log"

# ========== 执行rsync ==========
rsync -av --bwlimit=150M --size-only --inplace $LINK_PARAM "$SOURCE" "$CURRENT_BACKUP"
RETURN_CODE=$?

# ========== 判断备份状态 ==========
case $RETURN_CODE in
    0)  FINAL_STATUS="完成" ;;
    23) FINAL_STATUS="完成（部分文件失败）" ;;
    20) FINAL_STATUS="失败（用户取消）" ;;
    30) FINAL_STATUS="失败（传输中断）" ;;
    *)
        if grep -q "No space left on device" "${CURRENT_BACKUP}/rsync详细日志.log"; then
            FINAL_STATUS="失败（磁盘空间不足）"
        else
            FINAL_STATUS="失败（错误码$RETURN_CODE）"
        fi
        ;;
esac

# ========== 重命名备份目录 ==========
FINAL_BACKUP="${BACKUP_ROOT}/服务器副本_${TIMESTAMP}_${FINAL_STATUS}"
mv "$CURRENT_BACKUP" "$FINAL_BACKUP"

# ========== 关键错误提取（置顶2000行） ==========
{
    # 保留原日志头
    head -n 10 "$MAIN_LOG"
    
    # 如果是部分失败，提取错误文件列表
    if [ "$RETURN_CODE" -eq 23 ]; then
        echo "======= 失败文件列表（最近2000行） ======="
        grep "failed" "${FINAL_BACKUP}/rsync详细日志.log" | head -n 2000
        echo "====================================="
    fi
    
    # 追加最新日志（排除已显示内容）
    tail -n +11 "$MAIN_LOG" | grep -v "failed"
} > "${MAIN_LOG}.tmp" && mv "${MAIN_LOG}.tmp" "$MAIN_LOG"

# ========== 日志轮换（总保留5000行） ==========
tail -n 5000 "$MAIN_LOG" > "${MAIN_LOG}.tmp" && mv "${MAIN_LOG}.tmp" "$MAIN_LOG"

# ========== 清理锁文件 ==========
rm -f "$LOCK_FILE"
exit $RETURN_CODE